package com.luck

import android.os.Bundle
import android.util.Log
import android.webkit.*
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.OnBackPressedCallback
import androidx.core.net.toUri

class MainActivity : ComponentActivity() {

    private val tag = "MainActivity" // 修改为小写风格
    private val trustedUrl = "http://106.14.249.253/app/"

    private fun isNetworkAvailable(): Boolean {
        val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val network = connectivityManager.activeNetwork ?: return false
        val capabilities = connectivityManager.getNetworkCapabilities(network) ?: return false
        return capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
    }

    private fun isRunningOnEmulator(): Boolean {
        val buildProduct = android.os.Build.PRODUCT
        return buildProduct != null && (buildProduct.contains("sdk") || buildProduct.contains("emulator"))
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        try {
            if (!isNetworkAvailable()) {
                Toast.makeText(this, "网络不可用，请检查网络连接", Toast.LENGTH_LONG).show()
                Log.e(tag, "网络不可用，无法加载应用")
                return
            }

            if (isRunningOnEmulator()) {
                Log.w(tag, "检测到应用运行在模拟器环境中，某些功能可能无法正常工作")
            }

            title = "青少年编程平台"
            setContentView(R.layout.activity_main) // 使用布局文件

            val webView = findViewById<WebView>(R.id.webView)
            configureWebView(webView)
            webView.loadUrl(trustedUrl)

            // 替换 onBackPressed，使用 OnBackPressedDispatcher
            onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
                override fun handleOnBackPressed() {
                    if (webView.canGoBack()) {
                        webView.goBack()
                    } else {
                        // 关闭 Activity
                        finish()
                    }
                }
            })
        } catch (e: Exception) {
            Log.e(tag, "应用启动时发生异常: ${e.message}", e) // 捕获并记录异常
            Toast.makeText(this, "应用启动失败，请重试或联系管理员", Toast.LENGTH_LONG).show()
        }
    }

    private fun configureWebView(webView: WebView) {
        webView.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
                val url = request?.url.toString()
                Log.d(tag, "尝试加载 URL: $url")
                // 处理非 http/https 协议
                if (!url.startsWith("http://") && !url.startsWith("https://")) {
                    try {
                        val intent = android.content.Intent(android.content.Intent.ACTION_VIEW, url.toUri())
                        view?.context?.startActivity(intent)
                    } catch (e: Exception) {
                        Log.w(tag, "无法处理的 URL scheme: $url")
                    }
                    return true // 已处理
                }
                return false // 允许 WebView 继续加载
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                Log.d(tag, "页面加载完成: $url") // 添加日志记录
                if (url?.startsWith(trustedUrl) == true) {
                    Log.d(tag, "加载的页面属于可信域名: $url")
                } else {
                    Log.w(tag, "加载的页面不属于可信域名: $url")
                }
            }
        }

        val webSettings = webView.settings
        // 启用 JavaScript 可能带来 XSS 风险，请确保仅加载可信内容
        webSettings.javaScriptEnabled = true // ⚠️ 注意：启用 JavaScript 可能导致 XSS 漏洞
        webSettings.domStorageEnabled = true // 启用 DOM 存储
        webSettings.cacheMode = WebSettings.LOAD_DEFAULT // 设置缓存模式
        Log.d(tag, "WebView 配置完成")
    }
}
